package cc.angis.xiugallery;

import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cc.angis.xiugallery.data.PostData;
import cc.angis.xiugallery.image.util.CropImageDetailLoader;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageCache.ImageCacheParams;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.image.util.Utils;
import cc.angis.xiugallery.provider.ISourceProvider;
import cc.angis.xiugallery.provider.PostListProvider;
import cc.angis.xiugallery.util.CommentLoader;

import com.actionbarsherlock.app.SherlockListFragment;

public class PostListFragment extends SherlockListFragment{
    private static final String TAG = "PostListFragment";
    private static final String IMAGE_CACHE_DIR = "thumbs";
    private ISourceProvider mSourceProvider;
//    private Handler imageHandler;
    private ImageResizer mImageWorker;
    
    private CommentLoader commentLoader;
    
    /**
     * Empty constructor as per the Fragment documentation
     */
    public PostListFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSourceProvider = new PostListProvider(getActivity());
        mSourceProvider.initSource();
        commentLoader = new CommentLoader(getActivity());
        // The ImageWorker takes care of loading images into our ImageView children asynchronously

        setHasOptionsMenu(true);
        
        PostAdapter adapter = new PostAdapter(getActivity());
        for (int i=0;i <mSourceProvider.getSize(); i++){
        	adapter.add((PostData)mSourceProvider.getItem(i));
        }
		setListAdapter(adapter);
    }
    

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.postlist, container, false);
        return v;
    }
    
    public class PostAdapter extends ArrayAdapter<PostData> {

		public PostAdapter(Context context) {
			super(context, 0);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ImageView imgView;
			TextView postContent;
			View commentView;
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.postitem, null);
			}
			imgView = (ImageView) convertView.findViewById(R.id.imgView);
			postContent = (TextView) convertView.findViewById(R.id.postcontent);
			commentView = convertView.findViewById(R.id.commentLayout);
			mImageWorker.loadImage(position, imgView);
			postContent.setText(getItem(position).getContent());
			commentLoader.loadLastCommentByPostId(getItem(position).getPostId(), commentView);
			return convertView;
		}
		
		@Override
	    public int getCount() {
	        // Size of adapter + number of columns for top empty row
	        return mSourceProvider.getSize();
	    }

	    @Override
	    public PostData getItem(int position) {
	    	return (PostData)mSourceProvider.getItem(position);
	    }

	    @Override
	    public long getItemId(int position) {
	    	return ((PostData)mSourceProvider.getItem(position)).getId();
	    }
	}
    
    
    @Override
    public void onResume() {
        super.onResume();
//        mSourceProvider.initSource();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
//        final Intent i = new Intent(getActivity(), ImageGridActivity.class);
//        i.putExtra(GlobalConst.INTENT_BUCKET_ID,  mSourceProvider.getItem(position).toString());
//        i.putExtra(GlobalConst.INTENT_GROUP_TYPE, GlobalConst.INTENT_GROUP_TYPE_FAVOURITE);
//        startActivity(i);
    }

    

	@Override
	public void onDestroyView() {
		final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
        }
		super.onDestroyView();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        width = width - 2 * getResources().getDimensionPixelSize(R.dimen.postlist_listviewpadding);
        int height = getResources().getDimensionPixelSize(R.dimen.postlist_imgheight);
		 mImageWorker = new CropImageDetailLoader(getActivity(), width, height);
	        mImageWorker.setAdapter(mSourceProvider);
	        mImageWorker.setLoadingImage(R.drawable.empty_photo);
	        ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);

	        // Allocate a third of the per-app memory limit to the bitmap memory cache. This value
	        // should be chosen carefully based on a number of factors. Refer to the corresponding
	        // Android Training class for more discussion:
	        // http://developer.android.com/training/displaying-bitmaps/
	        // In this case, we aren't using memory for much else other than this activity and the
	        // ImageDetailActivity so a third lets us keep all our sample image thumbnails in memory
	        // at once.
	        cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(getActivity()) / 3;
	        mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(), cacheParams));
	}

//	@Override
//	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		if (mSourceProvider != null && mSourceProvider.getSize() > 0){
//			SubMenu sub = menu.addSubMenu("Theme");
//			sub.setIcon(R.drawable.ic_action_search);
//	        sub.add(Menu.NONE, R.id.add_fav_button, 0, getString(R.string.menu_addfavourite));
//	        sub.add(Menu.NONE, R.id.del_fav_button, 1, getString(R.string.menu_delfavourite));
//	        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		} else
//			inflater.inflate(R.menu.menu1, menu);
//		super.onCreateOptionsMenu(menu, inflater);
//	}
//	
//	@Override
//	public boolean onOptionsItemSelected(
//			com.actionbarsherlock.view.MenuItem item) {
//		switch(item.getItemId()){
//			case android.R.id.home:
//				if (getActivity() instanceof SlidingFragmentActivity){
//					((SlidingFragmentActivity)getActivity()).getSlidingMenu().showBehind();
//				} else
//					getActivity().finish();
//				break;
//			case R.id.add_fav_button:
//				final Intent i = new Intent(getActivity(), AddFavouriteActivity.class);
//		        startActivityForResult(i, 0);
//				break;
//			case R.id.del_fav_button:
//				break;
//			default:
//				break;
//		}
//		return super.onOptionsItemSelected(item);
//	}

}

